#!/usr/local/bin/python2.7
# Parse the "bunny.iv" point-cloud stuff from
# http://www.cc.gatech.edu/projects/large_models/bunny.html
# --
# GPL V3
# Copyright 2017 Chris Baird,, <cjb@brushtail.apana.org.au>

foo = open("bunny.iv")

xmin = 0.0
xmax = 0.0
ymin = 0.0
ymax = 0.0
zmin = 0.0
zmax = 0.0

while 1:
  v = foo.readline()
  if v == "":
        break;
  (xs, ys, zs)=v.split()
  xf = float(xs)
  yf = float(ys)
  zf = float(zs)

  if xf < xmin:
    xmin = xf
  if xf > xmax:
    xmax = xf

  if yf < ymin:
    ymin = yf
  if yf > ymax:
    ymax = yf

  if zf < zmin:
    zmin = zf
  if zf > zmax:
    zmax = zf

foo.close

xd = xmax - xmin
yd = ymax - ymin
zd = zmax - zmin

xmid = xd / 2.0
ymid = yd / 2.0
zmid = zd / 2.0

print "xmin = ", xmin, "xmax = ",xmax, "xd = ", xd, "xmid = ", xmid
print "ymin = ", ymin, "ymax = ",ymax, "yd = ", yd, "ymid = ", ymid
print "zmin = ", zmin, "zmax = ",zmax, "zd = ", zd, "zmid = ", zmid

scaling = 0.0

if (xd > yd) & (xd > zd):
  scaling = xd
if (yd > zd) & (yd > zd):
  scaling = yd
if (zd > xd) & (zd > yd):
  scaling = zd

intscale = int(32768/scaling)

print "scaling = ", scaling, "intscale = ", intscale

######################################################################

foo = open("bunny.iv")

bunnypoints = []

while 1:
  v = foo.readline()
  if v == "":
        break;
  (xs, ys, zs)=v.split()
  xf = float(xs) - xmin - xmid
  yf = float(ys) - ymin - ymid
  zf = float(zs) - zmin - zmid

  xi = int(xf * intscale)
  yi = int(yf * intscale)
  zi = int(zf * intscale)

  #if xi < 0:
  #  xi = 65536 + xi
  #if yi < 0:
  #  yi = 65536 + yi
  #if zi < 0:
  #  zi = 65536 + zi

  bunnypoints.append( (xi, yi, zi))

foo.close()

bunnysize=len(bunnypoints)
print "bunnysize=", bunnysize

######################################################################

#from graphics import *

bar = open ("bunnydata", "w")

#s = [[]]
#s = [[-1 for i in xrange(320)] for i in xrange(200)]

#win = GraphWin("Stanford Bunny", 640, 400)

for i in range (0, bunnysize, bunnysize/4800):
  (xi, yi, zi) = bunnypoints[i]
  bar.write( str(xi) + "," + str(yi) + "," + str(zi) + ",\n")

  #if xi > 32767:
  #  xi -= 65536;
  #if yi > 32767:
  #  yi -= 65536
  #if zi > 32767:
  #  zi -= 65536

  x = 160 + int( (220*xi) /32768)
  y = 120 - int( (220*yi) /32768)

  #d = int((256*zi) /32768)
  #d = 0
  #if d > s[x][y]:
  #s[x][y] = d
  #pt.setFill(color_rgb(d, d, d))

  #if (x >= 0) & (x < 320) & (y >= 0) & (y < 200):
  #  pt = Point(x*2,y*2)
  #  pt.draw(win)


print "Done"
#time.sleep(5)
bar.close()
